package com.batyuta;

import org.apache.log4j.Logger;

import java.util.HashSet;
import java.util.Set;


/**
 * User: alexey
 * Date: 6/24/11
 */
public class MyListRevert {
    private static Logger logger = Logger.getLogger(MyListRevert.class);

    public static class MyItem {
        private MyItem next;
        private String data;

        public MyItem(MyItem next, String data) {
            this.next = next;
            this.data = data;
        }

        public MyItem getNext() {
            return next;
        }

        public void setNext(MyItem next) {
            this.next = next;
        }

        public String getData() {
            return data;
        }

        @Override
        public String toString() {
            Set<MyItem> antiCycle = new HashSet<MyItem>();
            MyItem result = this;
            StringBuffer sb = new StringBuffer();
            int i = 0;
            do {
                if (antiCycle.contains(result)) {
                    if (i++ > 25) {
                        break;
                    }
                } else {
                    antiCycle.add(result);
                }
                sb.append(result.getData());
                sb.append("-->");
                result = result.getNext();
            } while ((result != null));
            sb.append("null");
            return sb.toString();
        }
    }

    public static void main(String[] args) {
        MyItem result = null;
        for (int i = 5; i >= 0; i--) {
            result = new MyItem(result, "" + i);
        }

        result = revert(result);

    }

    public static MyItem revert(MyItem in) {
        logger.info("IN:  \n"+in);
        if (null == in) {
            return null;
        }
        MyItem pre = null;
        MyItem next;
        int i = 0;
        do {
            logger.debug("\nCycle: " + i);
            logger.debug("\tIN:   " + in);
            logger.debug("\tPRE:  " + pre);
            next = in.getNext();
            logger.debug("\tNEXT: " + next);
            in.setNext(pre);
            logger.debug("\tIN:   " + next);
            pre = in;
            logger.debug("\tPRE:  " + pre);
            in = next;
            logger.debug("\tIN:   " + in);
            i++;
        } while ((in != null));
        logger.info("OUT: \n"+pre);
        return pre;
    }
}
